package com.ruoyi.webSocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

@Component
public class DeviceWebSocket extends TextWebSocketHandler {
    // 保存所有连接的客户端会话
    private static final CopyOnWriteArrayList<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    private static ObjectMapper objectMapper = new ObjectMapper(); // 静态使用

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        sessions.add(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        sessions.remove(session);
    }

    // 公共发送方法
    private static void sendMessage(DeviceMessage message) {
        try {
            String json = objectMapper.writeValueAsString(message);
            for (WebSocketSession session : sessions) {
                if (session.isOpen()) {
                    session.sendMessage(new TextMessage(json));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 发送设备状态
    public static void broadcastDeviceStatus(String deviceId, boolean isOnline) {
        DeviceMessage msg = new DeviceMessage("status", deviceId,
                Map.of("status", isOnline)
        );
        sendMessage(msg);
    }

    public static void broadcastDeviceTelemetry(String deviceId, String voltage) {
        DeviceMessage msg = new DeviceMessage("data", deviceId,
                Map.of("voltage", voltage == null ? "" : voltage)
        );
        sendMessage(msg);
    }

    // 发送设备异常
    public static void broadcastDeviceAbnormality(String deviceId, String workStatus, String message) {
        DeviceMessage msg = new DeviceMessage("abnormal", deviceId,
                Map.of(
                        "workStatus", workStatus,
                        "message", message,
                        "code", 5001  // 可扩展
                )
        );
        sendMessage(msg);
    }

    // 发送设备文本数据
    public static void broadcastDeviceText(String deviceId, String data) {
        DeviceMessage msg = new DeviceMessage("data", deviceId,
                Map.of("content", data)
        );
        sendMessage(msg);
    }
}